//
//  JSONAnalysis.m
//  CookMenu
//
//  Created by 郭晓敏 on 14-7-21.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "JSONAnalysis.h"
#import "NETAysnConnection.h"
@implementation JSONAnalysis
{
    NSMutableData *_receiveData;
    NETAysnConnection *_connection;
    DidFailBlocks   _didFailBlock;
    DidFinishBlocks _didFinishBlock;
}

#pragma mark 初始化方法
//  1、初始化方法(指定)
-(instancetype)initWithRequest:(NSURLRequest *)request
{
    self = [super init];
    if (self) {
        _connection = [[NETAysnConnection alloc] initWithRequest:request];
        [self setupConnection];
    }
    
    return self;
    
}

//  2、初始化方法POST
-(instancetype)initWithPOSTRequest:(NSString *)request
                              body:(NSString *)body
{
    self = [super init];
    if (self) {
        _connection = [NETAysnConnection asynCOnnectionwithPOSTRequest:request body:body];
        [self setupConnection];
    }
    return self;
    
}

//  3、初始化方法 GET
-(instancetype)initWithGETRequest:(NSString *)request
{
    self = [super init];
    if (self) {
        _connection = [NETAysnConnection asynConnectionWithGetRequest:request];
        [self setupConnection];
    }
    return self;
}

#pragma mark 回调方法
//  回调方法---数据加载已经结束
-(void)didFinishUsingBlock:(DidFinishBlocks)didFinsh
{
    _didFinishBlock = [didFinsh copy];
}

//  回调方法---数据加载失败
-(void)didFailUsingBlock:(DidFailBlocks)didFail
{
    _didFailBlock = [didFail copy];
}


#pragma mark 加载链接
-(void)setupConnection
{
    _receiveData  = [NSMutableData dataWithCapacity:1];
    // 接收到数据回调 block
    [_connection didReceiveDataUsingBlock:^(NSData *data) {
        [self didReiceivedData:data];
    }];
    //  接收数据完成回调方法
    [_connection didFinishLoadingUsingBlock:^{
        [self  didFinishLoad];
    }];
    //  接收数据失败毁掉方法
    [_connection didFailedUsingBlock:^(NSError *error) {
        [self didFail:error];
    }];
    
    
}

//  已经接收到数据
- (void)didReiceivedData:(NSData *)data {
    [_receiveData appendData:data];
}


//  已经完成加载
- (void)didFinishLoad {
    NSError * error;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:_receiveData options:NSJSONReadingAllowFragments error:&error];
    if(error && _didFailBlock) {
        _didFailBlock(error);
    }else {
        if(_didFinishBlock) {
            _didFinishBlock(jsonObject);
        }
    }
}

//  连接失败
- (void)didFail:(NSError *)error {
    if(_didFailBlock) {
        _didFailBlock(error);
    }
}


@end
